<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="6"
        ><div class="grid-content bg-purple">
          <el-input
            placeholder="请输入内容"
            v-model="getUsers.query"
            class="input-with-select"
            clearable
            @clear="initList"
            @blur="initList"
            @keydown.enter.native="initList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="initList"
            ></el-button>
          </el-input></div
      ></el-col>
      <el-col :span="2"
        ><div class="grid-content bg-purple">
          <el-button type="primary" plain @click="addShow = true"
            >添加用户
          </el-button>
        </div></el-col
      >
    </el-row>
    <el-table :data="userList" stripe border style="width: 100% height:50px">
      <el-table-column type="id" prop="id" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="create_time" label="日期">
        <template slot-scope="scope">
          <div :addDate="scope.row.create_time">
            {{ scope.row.create_time | formatDate }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeUserState(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="getEditUser(scope.row)"
            ></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delUser(scope.row)"
            ></el-button>
          </el-tooltip>

          <el-tooltip
            class="item"
            effect="dark"
            content="分配角色"
            placement="top"
          >
            <el-button
              type="warning"
              circle
              icon="el-icon-s-custom"
              @click="getArUser(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="getUsers.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="getUsers.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 编辑用户弹框 -->
    <el-dialog :visible.sync="editShow" width="500px">
      <el-form :model="editForm" label-width="80px" ref="editUserForm">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser('editUserForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="addShow" width="500px">
      <el-form
        :model="addForm"
        label-width="80px"
        ref="addUserForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button
          type="primary"
          native-type="submit"
          @click="addUser('addUserForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog title="分配角色" :visible.sync="assignRolesShow" width="500px">
      <el-form :model="assignRolesUser" label-width="120px">
        <el-form-item label="当前用户">
          <el-input
            v-model="assignRolesUser.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-select v-model="roleId" placeholder="请选择角色" width="100%">
            <el-option
              v-for="(role, index) of roleList"
              :key="index"
              :label="role.roleName"
              :value="role.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignRolesShow = false">取 消</el-button>
        <el-button type="primary" @click="assignRoles()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getUsers,
  getSingleUser,
  editUser,
  changeUserState,
  delUser,
  addUser,
  assignRoles,
  getRoleList
} from "@/api/index";
export default {
  data() {
    return {
      // 获取用户列表
      getUsers: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      total: 0,
      // 编辑用户
      editShow: false,
      editForm: {
        username: "",
        email: "",
        mobile: "",
        id: 0
      },
      // 添加用户
      addShow: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 分配角色
      assignRolesShow: false,
      assignRolesUser: {},
      roleList: [],
      roleId: "",
      // 添加用户的表单验证
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }
        ],
        email: [
          {
            message: "请输入邮箱地址",
            trigger: "blur"
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur,change"
          }
        ],
        mobile: [
          {
            message: "电话不能为空"
          }
        ]
      }
    };
  },
  methods: {
    // 编辑
    async getEditUser(row) {
      await getSingleUser(row.id).then(res => {
        if (res.meta.status === 200) {
          this.editForm.username = res.data.username;
          this.editForm.email = res.data.email;
          this.editForm.mobile = res.data.mobile;
          this.editForm.id = res.data.id;
        } else {
          this.$message.warning(res.meta.msg);
        }
      });
      this.editShow = true;
    },
    async editUser(formName) {
      await this.$refs[formName].validate(valide => {
        if (valide) {
          editUser(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.$message.success("修改成功");
              this.editShow = false;
              this.initList();
            } else {
              this.$message.warning(res.meta.msg);
            }
          });
        }
      });
    },
    // 获取用户列表
    async initList() {
      let {
        data: { users, total, pagenum }
      } = await getUsers({ params: this.getUsers });
      this.userList = users;
      this.total = total;
      this.pagenum = pagenum;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getUsers.pagesize = val;
      this.initList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getUsers.pagenum = val;
      this.initList();
    },
    // 删除
    async delUser(row) {
      this.$confirm("真的要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = delUser(row.id);
          data.meta.status == 200
            ? this.$message.success(data.meta.msg)
            : this.$message.warning(data.meta.msg);
          this.initList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 更改用户状态
    async changeUserState(row) {
      await changeUserState({ uid: row.id, type: row.mg_state }).then(res => {
        if (res.meta.status == 200) {
          this.$message.success("修改用户状态成功");
        } else {
          this.$message.warning(res.meta.msg);
        }
      });
    },
    // 添加用户
    async addUser(formName) {
      await this.$refs[formName].validate(valide => {
        if (valide) {
          addUser(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.$message.success(res.meta.msg);
            } else {
              this.$message.warning(res.meta.msg);
            }
            this.addShow = false;
            this.addForm.username = "";
            this.addForm.password = "";
            this.addForm.email = "";
            this.addForm.mobile = "";
            this.initList();
          });
        }
      });
    },
    // 分配用户角色
    async getArUser(row) {
      this.assignRolesUser = row;
      this.assignRolesShow = true;
      await getRoleList().then(res => {
        if (res.meta.status == 200) {
          this.roleList = res.data;
        }
      });
    },
    assignRoles() {
      if (!this.roleId) {
        this.$message.warning("请选择角色");
      } else {
        assignRoles({ id: this.assignRolesUser.id, rid: this.roleId }).then(
          res => {
            if (res.meta.status == 200) {
              this.$message.success("设置角色成功");
              this.assignRolesShow = false;
              this.initList();
            } else {
              this.$message.error(res.meta.msg);
            }
          }
        );
      }
    }
  },
  filters: {
    formatDate(date) {
      let val = new Date(date);
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let min = val.getMinutes();
      let sec = val.getSeconds();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hour = hour < 10 ? "0" + hour : hour;
      min = min < 10 ? "0" + min : min;
      sec = sec < 10 ? "0" + sec : sec;
      return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
    }
  },
  created() {
    this.initList();
  }
};
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-table {
  line-height: 0;
}
.el-col {
  line-height: 0;
}

.el-pagination {
  margin-top: 40px;
  height: 30px;
}
.el-dialog {
  line-height: 0;
}
.el-select {
  display: block;
}
.el-form-item__label {
  text-align: center;
}
.el-row {
  margin: 20px 0;
}
</style>
